<script setup>
import { reactive, ref, computed, onMounted, nextTick, onBeforeUnmount, toRefs } from 'vue';
import { useRoute } from 'vue-router';
import { CloseBold } from '@element-plus/icons-vue';
import {
  ElCascader,
  ElIcon,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
} from 'element-plus';
import _ from 'lodash-es';
import { getRelationById } from '@/apis/api-map-server';
import { load } from '@/common/common-loading';
import BorderBoxBg from '@/components/BorderBoxBg.vue';
import { LAYERS_GROUP_ID } from '@/utils/map-helper';
import {
  ADD_LAYER_TO_MAP_BOX_MAP,
  AGENCY_MAP_SERVER,
  GET_CONDITION_QUERY,
  MAP_ADD_CIRCLE_BRIGHT,
  High_Light_Dotted_Line_LAYER,
} from '@/utils/map-utils';
import { REMOVE_MAPBOX_LAYER } from '@/utils/map-utils';

const props = defineProps({
  toolbarRight: {
    type: String,
    default: '5.3125rem',
  },
});
const { toolbarRight } = toRefs(props);

const emit = defineEmits(['termingClose']);

const route = useRoute();

const cascaderProps = {
  emitPath: false,
};

const mapImgList = ref([]);
const layerValue = ref('');
const checked_layer = ref('1');
const field_type = ref('String');
const query_list_table = ref([]);
const currentRow = ref([]);
const singleTableRef = ref();

const state = reactive({
  table_show: false,
  list_detail: false,
  s_showByRow: false,
  styleObject: {},
  query_info: [],
});

const query_value = ref({
  field: '',
  condition: '等于',
  content: '',
});

const condition_option = ref([
  {
    label: '等于',
    value: '等于',
  },
]);

const rowCount = computed(() => {
  return Math.ceil(currentRow.value.length / 1);
});

const getRelationByIdApi = async () => {
  const [err, data] = await getRelationById({
    menuCode: route.query?.code,
  });

  if (!err) {
    mapImgList.value = data.map((item) => {
      return {
        ...item,
        label: item.serviceName,
        value: item.serviceName,
        children:
          item?.children?.map((el) => {
            let id = `${item.id}${Math.random()}`;

            return {
              ...el,
              fid: item.id,
              id,
              label: el.layerMeta.name,
              value: id,
              url: AGENCY_MAP_SERVER(item, el),
            };
          }) || [],
      };
    });
  }
};

onMounted(() => {
  getRelationByIdApi();
});

const layerList = computed(() => {
  return mapImgList.value.map((item) => item?.children || []).flat(1);
});

//图层选择
const handleChange = (e) => {
  handleBtnQuery(2);

  let target = layerList.value.find((el) => el.id == e);

  if (target) {
    checked_layer.value = target;

    nextTick(() => {
      ADD_LAYER_TO_MAP_BOX_MAP(LAYERS_GROUP_ID.TD_MAP_LAYER, target);
    });
  }
};

// 选择字段
const handleChangeOptionField = (e) => {
  handleBtnQuery(2);

  query_value.value.field = e;
  query_value.value.condition = '等于';

  const field = checked_layer.value?.layerMeta?.fields.find(function (i) {
    return i.name === e;
  });

  if (field.type == 'String') {
    condition_option.value = [
      {
        label: '等于',
        value: '等于',
      },
    ];
    field_type.value = 'String';

    query_value.value.content = '';
  } else {
    condition_option.value = [
      {
        label: '等于',
        value: '等于',
      },
      {
        label: '大于等于',
        value: '大于等于',
      },
      {
        label: '大于',
        value: '大于',
      },
      {
        label: '小于等于',
        value: '小于等于',
      },
      {
        label: '小于',
        value: '小于',
      },
    ];

    field_type.value = 'Number';
    query_value.value.content = 0;
  }
};

// 选择条件

const handleChangeOptionCondition = (e) => {
  query_value.value.condition = e;
};

// 重置/查找
const handleBtnQuery = async (type) => {
  if (type == 2) {
    handleReset();

    condition_option.value = [
      {
        label: '等于',
        value: '等于',
      },
    ];

    field_type.value = 'String';
    state.table_show = false;
    state.list_detail = false;
  } else if (type == 1) {
    if (checked_layer.value == 1) {
      ElMessage({
        message: '请选择图层',
        duration: 1000,
        type: 'warning',
      });

      return;
    }

    if (query_value.value.field == '' || query_value.value.field == 1) {
      ElMessage({
        message: '请选择字段',
        duration: 1000,
        type: 'warning',
      });

      return;
    }

    if (query_value.value.condition == '' || query_value.value.condition == 1) {
      ElMessage({
        message: '请选择条件',
        duration: 1000,
        type: 'warning',
      });

      return;
    }

    if (
      (query_value.value.content == '' && field_type.value == 'String') ||
      (query_value.value.content == null && field_type.value == 'Number')
    ) {
      ElMessage({
        message: '请输入内容',
        duration: 1000,
        type: 'warning',
      });

      return;
    }

    load.show('正在获取数据，请稍等...');

    let mapParams = {
      id: checked_layer.value.fid,
      TYPENAME: checked_layer.value.label.replace('.shp', ''),
      CQL_FILTER: encodeURI(
        [query_value.value]
          .map(
            (filter) =>
              `"${filter.field}"${
                filter.condition == '等于'
                  ? '='
                  : filter.condition == '大于等于'
                  ? '>='
                  : filter.condition == '大于'
                  ? '>'
                  : filter.condition == '小于等于'
                  ? '<='
                  : '<'
              } '${filter.content}'`,
          )
          .join(' ')
          .trim(),
      ),
    };

    const resultInfo = await GET_CONDITION_QUERY(mapParams);

    if (!resultInfo.features.length) {
      ElMessage({
        message: '未查询到任何符合要求的数据要素',
        duration: 1000,
        type: 'warning',
      });
      state.list_detail = false;
      state.table_show = false;

      clearLightDottedLayer();
      state.query_info = [];
      load.hide();

      return;
    }

    state.query_info = resultInfo.features;

    const tackle_value = _.map(resultInfo.features, function (feature) {
      feature.properties.geometry = feature.geometry;

      return feature.properties;
    });

    const arr_info = [];

    for (let i = 0; i < tackle_value.length; i++) {
      const el = tackle_value[i];
      const obj = {};

      obj.fieldValue = el[query_value.value.field];
      obj.layer = checked_layer.value.label;
      obj.field = query_value.value.field;
      obj.geometry = el.geometry;
      obj.all = el;
      arr_info.push(obj);
    }

    query_list_table.value = arr_info;

    load.hide();
    state.table_show = true;
  }
};

// 点击表格查看详情
const handleCurrentChange = (val) => {
  clearLightDottedLayer();
  if (val == null) return;

  if (Object.hasOwn(val, 'geometry')) {
    const layerId = LAYERS_GROUP_ID.High_Light_RESULT_LAYER;

    const arr = [
      {
        key: '字段',
        value: '字段值',
      },
    ];

    const { geometry, ...newPet } = val.all;

    if (geometry?.type == 'Point') {
      MAP_ADD_CIRCLE_BRIGHT(val.all);
    } else {
      High_Light_Dotted_Line_LAYER(layerId, geometry);
    }

    for (let key in newPet) {
      let info = {};

      info['key'] = key;
      info['value'] = val.all[key];

      arr.push(info);
    }

    currentRow.value = arr;

    state.list_detail = true;
    state.styleObject = { width: '600px' };
  }
};

// 关闭详情窗口
const handleCloseQueryDetail = (row) => {
  state.list_detail = false;
  clearLightDottedLayer();

  singleTableRef.value.setCurrentRow(row);
};

// 重置
const handleReset = () => {
  query_value.value.field = '';
  query_value.value.condition = '等于';
  query_value.value.content = '';
  clearLightDottedLayer();
};

// 清除高亮图层(虚线)
const clearLightDottedLayer = () => {
  const map = window.map2d;
  const layerId = LAYERS_GROUP_ID.High_Light_RESULT_LAYER;

  REMOVE_MAPBOX_LAYER(LAYERS_GROUP_ID.High_Light_RESULT_LAYER);

  if (map && map.getLayer(`${layerId}~DottedLight`)) {
    map.removeLayer(`${layerId}~DottedLight`);
    map.removeSource(`${layerId}~DottedLight`);
  }
};

// 关闭弹窗 并清理数据
const handleClose = () => {
  clearLightDottedLayer();
  REMOVE_MAPBOX_LAYER(LAYERS_GROUP_ID.TD_MAP_LAYER);

  emit('termingClose');
};

onBeforeUnmount(() => {
  handleClose();
});
</script>
<template>
  <div>
    <BorderBoxBg title="条件查询" class="terming bottom-52px" :right="toolbarRight" @close="handleClose">
      <div class="cutting-box">
        <div class="item">
          <p>选择图层</p>
          <ElCascader
            v-model="layerValue"
            popper-class="cutting-pop bg-blue-400"
            class="pops"
            placeholder="选择图层"
            :options="mapImgList"
            :props="cascaderProps"
            style="width: 100%"
            @change="handleChange"
          />
        </div>
        <div class="item">
          <p>选择字段</p>
          <ElSelect v-model="query_value.field" placeholder="请选择字段" @change="(e) => handleChangeOptionField(e)">
            <ElOption value="1" label="请选择字段">请选择字段</ElOption>
            <ElOption
              v-for="(item, index) in checked_layer?.layerMeta?.fields"
              :key="index"
              :label="item.name"
              :value="item.name"
            />
          </ElSelect>
        </div>
        <div class="item">
          <p>选择条件</p>
          <ElSelect
            v-model="query_value.condition"
            placeholder="请选择条件"
            @change="(e) => handleChangeOptionCondition(e)"
          >
            <ElOption value="1" label="请选择条件">请选择条件</ElOption>
            <ElOption v-for="item in condition_option" :key="item.label" :label="item.label" :value="item.value" />
          </ElSelect>
        </div>
        <div class="item">
          <p>输入内容</p>
          <ElInput
            v-if="field_type == 'String'"
            v-model.trim="query_value.content"
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            maxlength="20"
            show-word-limit
          />
          <ElInputNumber
            v-if="field_type == 'Number'"
            v-model="query_value.content"
            controls-position="right"
            placeholder="请输入内容"
            style="width: 100%"
          />
        </div>
        <div class="btn_div">
          <div class="btn_select" @click="handleBtnQuery(1)">
            <p>查找</p>
          </div>
          <div class="btn_select" @click="handleBtnQuery(2)">
            <p>重置</p>
          </div>
        </div>
        <div v-if="state.table_show" class="list_query_style">
          <p>查询结果（点击查看详情）</p>
          <ElTable
            ref="singleTableRef"
            highlight-current-row
            :data="query_list_table"
            border
            class="table_border"
            height="250"
            :header-cell-style="{
              color: '#333333',
              background: 'rgba(97, 186, 55, 0.06)',
              textAlign: 'center',
            }"
            @current-change="handleCurrentChange"
          >
            <ElTableColumn prop="fieldValue" label="字段值" align="center">
              <template #default="scope">
                <span :title="scope.row.fieldValue" class="content-style">{{ scope.row.fieldValue }}</span>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="layer" label="图层" align="center">
              <template #default="scope">
                <span :title="scope.row.layer" class="content-style">{{ scope.row.layer }}</span>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="field" label="字段" align="center">
              <template #default="scope">
                <span :title="scope.row.field" class="content-style">{{ scope.row.field }}</span>
              </template>
            </ElTableColumn>
          </ElTable>
        </div>
      </div>
    </BorderBoxBg>

    <div v-show="state.list_detail" class="map_list_detail_root">
      <header>
        <span class="title">详情</span>
        <ElIcon class="root_icon_close" @click="handleCloseQueryDetail()">
          <CloseBold />
        </ElIcon>
      </header>
      <main>
        <p>图层：{{ checked_layer.label }}</p>
        <div class="table_main">
          <table v-if="s_showByRow" class="mailTable" :style="styleObject">
            <tr v-for="index in rowCount" :key="index">
              <th class="column">
                {{ currentRow[index * 2 - 2].key }}
              </th>
              <td>{{ currentRow[index * 2 - 2].value }}</td>
            </tr>
          </table>
          <table v-else class="mailTable" :style="styleObject">
            <tr v-for="index in rowCount" :key="index">
              <th class="column">{{ currentRow[index - 1].key }}</th>
              <td>{{ currentRow[index - 1].value }}</td>
            </tr>
          </table>
        </div>
      </main>
    </div>
  </div>
</template>

<style scoped lang="scss">
.terming {
  top: 10%;
  bottom: auto;
  width: 300px !important;
  .btn_div {
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 0 5px;
    text-align: center;
    .btn_select {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 110px;
      height: 42px;
      margin-top: 21px;
      margin-bottom: 17px;
      font-size: 16px;
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      p {
        margin: 0;
      }
      &:hover {
        background-color: #e6f5fe;
      }
      &:first-child {
        color: #33c7d4;
        background: rgba(25, 131, 145, 0.3);
      }
      &:nth-child(2) {
        color: #999999;
        background: rgba(153, 153, 153, 0.3);
      }
    }
  }
  .list_query_style {
    position: relative;
    bottom: 11px;
    background-color: none !important;

    p {
      color: #333333;
      font-weight: 400;
      font-size: 14px;
      line-height: 28px;
      text-align: left;
    }
    .table_border {
      width: 100%;
      height: 165px;
      margin-bottom: 25px;
      background-color: none !important;
      border-color: #c1c1c1;
      border-radius: 2px;
      .content-style {
        display: -webkit-box;
        overflow: hidden;
        text-overflow: ellipsis;
        background-color: none !important;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
    }
  }
}

.map_list_detail_root {
  position: absolute;
  top: 81px;
  left: 15px;
  z-index: 99999;
  width: 366px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 10px;
  box-shadow: 0px 0px 0.9px rgba(0, 0, 0, 0.02), 0px 0px 2.1px rgba(0, 0, 0, 0.028), 0px 0px 3.9px rgba(0, 0, 0, 0.035),
    0px 0px 6.9px rgba(0, 0, 0, 0.042), 0px 0px 13px rgba(0, 0, 0, 0.05), 0px 0px 31px rgba(0, 0, 0, 0.07);
  header {
    display: flex;
    justify-content: space-between;
    height: 42px;
    padding: 9px 13px 10px 17px;
    border-bottom: 1px solid #c1c1c1;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    .title {
      color: #ffffff;
      font-weight: 600;
      font-size: 17px;
      line-height: 1.5;
      letter-spacing: 1px;
    }
    .root_icon_close {
      width: 21px;
      color: #ffffff;
      font-size: 20px;
      cursor: pointer;
      :hover {
        color: #61ba37;
      }
    }
  }
  main {
    padding-top: 16px;
    padding-left: 16px;
    p {
      color: #ffffff;
    }
    .table_main {
      max-height: 615px;
      margin-top: 15px;
      margin-bottom: 25px;
      overflow: auto;
      &::-webkit-scrollbar {
        display: none;
        width: 0 !important;
      }
      .mailTable,
      .mailTable tr,
      .mailTable tr td {
        border: 1px solid #c1c1c1;
      }
      .mailTable {
        width: 334px;
        color: #ffffff;
        font-size: 12px;
        border-collapse: collapse;
        tr {
          &:first-child {
            color: #ffffff;
            background-color: rgba(97, 186, 55, 0.06);
          }
        }
      }
      .mailTable tr td {
        box-sizing: border-box;
        width: 334px;
        height: 35px;
        padding: 0 10px;
        font-size: 14px;
        line-height: 20px;
        text-align: center;
        text-align: left;
        border: 1px solid #c1c1c1;
      }
      .mailTable tr td.column {
        color: #ffffff;
      }
      .mailTable tr th {
        box-sizing: border-box;
        width: 232px;
        height: 35px;
        padding: 0 10px;
        font-weight: 400;
        font-size: 14px;
        line-height: 20px;
        text-align: left;
        border: 1px solid #c1c1c1;
      }
    }
  }
}
</style>
